package com.example.jt_manager_web;

import com.example.jt_common.PicUploadResult;
import com.example.jt_common.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

@Controller
@RequestMapping("/pic")
public class PicController {
    @Value("${fastdfs.tracker_servers}")
    String trackservers=null;
    @Value("${IMAGE_SERVER}")
    String IMAGE_SERVER=null;

    @RequestMapping("/upload")
    @ResponseBody
    public PicUploadResult uploadFile(MultipartFile uploadFile)  {
        PicUploadResult result = new PicUploadResult();
        String filename = uploadFile.getOriginalFilename();
        if(!filename.matches("^.*(.jpg|.png|.jpeg|.gif|.bmp)$")){
            result.setError(1);
        }else{
            try {
                BufferedImage image = ImageIO.read(uploadFile.getInputStream());
                result.setHeight(String.valueOf(image.getHeight()));
                result.setWidth(String.valueOf(image.getWidth()));
            } catch (IOException e) {
                result.setError(1);
            }
            if(result.getError()==0){
                try {
                    String fileSuffix = filename.substring(filename.lastIndexOf(".")+1);
                    String url = new FileUtil().fileUpload(uploadFile.getBytes(),fileSuffix,trackservers);
                    System.out.println(url);
                    result.setUrl(IMAGE_SERVER+url);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
